<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
  <title>生命游戏</title>
  <style>
    body {
      margin: 0;
    }
    #scene {
      position: fixed;
      width: 100vw;
      height: 100vh;
      background-color: #fff;
    }
    .img {
      position: absolute;
      width: 48px;
      height: 48px;
    }
    .heart.beated {
      animation: shake 0.3s;
    }

    @keyframes shake {
      0% {
        transform: scaleX(1) translateX(0);
      }
      33% {
        transform: scaleX(1.5) translateX(-5px) translateY(5px);
      }
      66% {
        transform: scaleX(0.5) translateX(10px)  translateY(-10px);
      }
      100% {
        transform: scaleX(1);
      }
    }
  </style>
</head>
<body>
  <div id="scene"></div>
  <script>
    scene.addEventListener('touchstart', function(ev){
      // 禁用默认事件
      ev.preventDefault();
      // 如果点到可操作区域，触发对应操作
      if (ev.target.className.indexOf('img') > -1) {
        ev.target.click()
      }
    }, true)
    const sceneConfig = {
      x: 0,
      y: 0
    }
    // 新手村的第一棵树
    create({type: 'tree', x: 50, y: 100})
    create({type: 'heart', x: sceneConfig.x + 10, y: sceneConfig.y + 10})
    create({type: 'heart', x: sceneConfig.x + 60, y: sceneConfig.y + 10})
    create({type: 'heart', x: sceneConfig.x + 110, y: sceneConfig.y + 10})
    function create(config={}) {
      const { type } = config;
      const img = document.createElement('div');
      img.className = 'img';
      if (config.x) img.style.left = `${config.x - sceneConfig.x}px`;
      if (config.y) img.style.top = `${config.y - sceneConfig.y}px`;
      if (config.w) img.style.width = `${config.w}px`;
      if (config.h) img.style.height = `${config.h}px`;
      console.log(config.x)
      switch(type) {
        case 'tree':
          img.style.background='url("img/tree.svg")';
          break;
        case 'heart':
          img.style.background='url("img/heartFull.svg")';
          img.classList.add('heart');
          // 第一次被攻击
          img.onclick = function() {
            clearTimeout(window.heatBeatTimer);
            img.style.display = 'none';
            img.style.display = 'inline-block';
            img.classList.add('beated')
            window.heatBeatTimer = setTimeout(()=>{
              img.classList.remove('beated');
              img.style.background = 'url("img/heartHalf.svg")';
            }, 300)
          }
          break;
        default:
      }
      scene.appendChild(img);
    }
  </script>
</body>
</html>